package com.sk.bilibili.utils;

import com.sk.bilibili.other.NotLoginException;
import lombok.SneakyThrows;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 邵康
 * @date 2021/11/23 13:40
 */
public class BSessionUtils {

    private static final Map<String,Map<String,Object>> B_SESSION_MAP =new HashMap<>();
    public static final String B_SESSION_ID="bsessionid";
    private static final String MEMBER_ID_KEY="MEMBER_ID_KEY";
    private static final String LAST_LOGIN_DAY_KEY="LAST_LOGIN_DAY_KEY";
    private static final String SLIDE_CODE_OFFSET_KEY ="SLIDE_CODE_OFFSET_KEY";
    //TODO   测试使用
    private static Integer defaultMemberId;

    public static void setDefaultMemberId(Integer memberId) {
        defaultMemberId=memberId;
    }

    @SneakyThrows
    public static Integer getMemberId(){
        Object memberId = getSession().get(MEMBER_ID_KEY);
        if(memberId==null){
            if(defaultMemberId==0)throw new NotLoginException();
            return defaultMemberId;
        }
        return (Integer) memberId;
    }

    public static String setMemberId(Integer memberId){
        String bSessionId = getBSessionId();
        B_SESSION_MAP.get(bSessionId).put(MEMBER_ID_KEY,memberId);
        return bSessionId;
    }

    public static Map<String,Object> getSession(){
        String bSessionId = getBSessionId();
        return B_SESSION_MAP.get(bSessionId);
    }

    // 保证  bSessionId 一定有效    不要 随便调用
    public static String getBSessionId() {
        String bSessionId=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest().getHeader(B_SESSION_ID);
        if(bSessionId==null||bSessionId.length()!=32){
            bSessionId= UUID.randomUUID().toString().replaceAll("-","");
        }
        if(!B_SESSION_MAP.containsKey(bSessionId)){
            B_SESSION_MAP.put(bSessionId,new HashMap<>());
            ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse()
                    .setHeader(B_SESSION_ID,bSessionId);
        }
        return bSessionId;
    }

    public static void invalidate() {
        B_SESSION_MAP.remove(getBSessionId());
    }

    // 用户频繁 退出 登录 操作 可以刷 硬币  不过 有 Redis二重判断
    public static Long getLastLoginDay() {
        Object lastLoginDay = getSession().get(LAST_LOGIN_DAY_KEY);
        if(lastLoginDay==null)return 0L;
        return (Long) lastLoginDay;
    }

    public static void setLastLoginDay(Long lastLoginDay) {
        getSession().put(LAST_LOGIN_DAY_KEY,lastLoginDay);
    }

    public static void setSlideCodeOffset(Integer offset) {
        getSession().put(SLIDE_CODE_OFFSET_KEY,offset);
    }

    public static Integer getSlideCodeOffset() {
        return (Integer) getSession().get(SLIDE_CODE_OFFSET_KEY);
    }

}
